package com.project.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.project.dto.MaterialCategoryDTO;
import com.project.dto.MaterialCategoryPageQueryDTO;
import com.project.entity.MaterialCategories;

import com.project.mapper.MaterialCategoryMapper;
import com.project.result.PageResult;
import com.project.service.MaterialCategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MaterialCategoryServiceImpl implements MaterialCategoryService {

    @Autowired
    private MaterialCategoryMapper materialCategoryMapper;

    @Override
    public void createCategory(MaterialCategoryDTO dto) {

        MaterialCategories categories = new MaterialCategories();
        BeanUtils.copyProperties(dto,categories);

        categories.setStatus(0);

        materialCategoryMapper.insert(categories);

    }

    @Override
    public void updateCategory(MaterialCategoryDTO dto) {
        MaterialCategories categories = new MaterialCategories();
        BeanUtils.copyProperties(dto,categories);
        materialCategoryMapper.updateById(categories);
    }

    @Override
    public void updateCategoryStatus(Integer status,Integer id) {
        MaterialCategories update = MaterialCategories.builder()
                .categoryId(id)
                .status(status)
                .build();
        materialCategoryMapper.updateById(update);
    }

    @Override
    public void deleteCategory(Integer categoryId) {
        //判断分类是否存在
        MaterialCategories category = materialCategoryMapper.selectById(categoryId);
        if (category == null) {
            throw new RuntimeException("材料分类不存在");
        }

        //判断分类状态是否为停用 只有状态为 停用0 时才允许删除
        if (category.getStatus() != 0) {
            throw new RuntimeException("请先停用该分类，再进行删除");
        }
        materialCategoryMapper.deleteById(categoryId);
    }

    @Override
    public PageResult pageQuery(MaterialCategoryPageQueryDTO queryDTO) {
        PageHelper.startPage(queryDTO.getPage(), queryDTO.getPageSize());
        Page<MaterialCategories> pageQuery = materialCategoryMapper.pageQuery(queryDTO);
        return new PageResult(pageQuery.getTotal(),pageQuery.getResult());
    }



}